package com.mass.core.framework.interceptor;

import io.jsonwebtoken.Claims;

import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.json.JSONObject;
import org.slf4j.LoggerFactory;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.ObjectUtils;
import org.springframework.util.PathMatcher;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.mass.core.token.JwtComponent;

/**
 * </p>
 *
 * @author liwenjun
 * @version 1.0.0
 * @date 2017/7/10 23:06
 */
public class PrivilegeInterceptor implements HandlerInterceptor {

    private static final org.slf4j.Logger logger = LoggerFactory.getLogger(PrivilegeInterceptor.class);

	private JwtComponent jwtComponent;
	
	public PrivilegeInterceptor(JwtComponent jwtComponent) {
		this.jwtComponent = jwtComponent;
	}

    public PrivilegeInterceptor() {
		super();
	}

	@SuppressWarnings("unused")
	private PathMatcher pathMatcher = new AntPathMatcher();

    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
        //System.out.println(">>>>>开始拦截器>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
        String uri = httpServletRequest.getRequestURI();
        String context = httpServletRequest.getServletContext().getContextPath();
        logger.debug("system context: " + context);
        uri = uri.substring(context.length());
        
        HttpSession session = httpServletRequest.getSession();
        
        Object object = session.getAttribute("sysUser");
        if(ObjectUtils.isEmpty(object)){
        	String authHeader = httpServletRequest.getHeader("jwtToke");
        	if(ObjectUtils.isEmpty(authHeader) ){
        		authHeader = httpServletRequest.getParameter("jwtToke");
        	}
            String tokenHead = "Bearer ";
            if (authHeader != null && authHeader.startsWith(tokenHead)) {
                String authToken = authHeader.substring(tokenHead.length());
                Claims claims = jwtComponent.parseJWT(authToken);
                if(ObjectUtils.isEmpty(claims)){
                	httpServletResponse.setContentType("application/json; charset=UTF-8");
                	PrintWriter out = null ;  
                	JSONObject res = new JSONObject();  
                	res.put("code","4000");  
                	res.put("message","token 超时或错误 !");
                	out = httpServletResponse.getWriter();  
                	out.append(res.toString());  
                	return false;  
                }
            }else{
            	httpServletResponse.setContentType("application/json; charset=UTF-8");
            	PrintWriter out = null ;  
            	JSONObject res = new JSONObject();  
            	res.put("code","5000");  
            	res.put("message","未登录 !");
            	out = httpServletResponse.getWriter();  
            	out.append(res.toString());  
            	return false;  
            }
        }
        return true;
    }

    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}
